package com.example.gpssystem.config;

import com.example.gpssystem.model.OperationLog;
import com.example.gpssystem.model.OperationLogRepository;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;

@Aspect
@Component
public class OperationLogAspect {
    
    @Autowired
    private OperationLogRepository logRepository;

    // 定义切入点表达式，匹配OrderService的删除方法
    @Pointcut("execution(* com.example.gpssystem.service.OrderService.deleteOrder(..))")
    public void deleteOrderOperation() {}

    @AfterReturning(pointcut = "deleteOrderOperation()", returning = "result")
    public void logSuccess(JoinPoint joinPoint, Object result) {
        saveLog(joinPoint, null);
    }

    @AfterThrowing(pointcut = "deleteOrderOperation()", throwing = "ex")
    public void logException(JoinPoint joinPoint, Throwable ex) {
        saveLog(joinPoint, ex.getMessage());
    }

    private void saveLog(JoinPoint joinPoint, String error) {
        OperationLog log = new OperationLog();
        log.setOperationTime(LocalDateTime.now());
        log.setMethod(joinPoint.getSignature().toShortString());
        log.setParameters(parseParams(joinPoint.getArgs()));
        log.setResult(error != null ? "失败: " + error : "成功");
        
        logRepository.save(log);
    }

    private String parseParams(Object[] args) {
        if (args == null || args.length == 0) return "";
        StringBuilder sb = new StringBuilder();
        for (Object arg : args) {
            sb.append(arg.toString()).append(",");
        }
        return sb.deleteCharAt(sb.length()-1).toString();
    }
}